const wx = require('weixin-js-sdk');

class Util {
  constructor() {
    this.userModel = this.getCookie('$mall') || void 0;
  }
  /**
   * 删除数组
   * @param {Array} data 初始对象
   * @param {String} id 唯一标识
   */
  removeArray(data, id) {
    for (let i = 0; i < data.length; i++) {
      if (String(data[i].id) === String(id)) {
        data.splice(i, 1);
        break;
      }
    }
    return data;
  }

  /**
   * 设置cookie
   * @param {String} name 名
   * @param {String} value 值 
   * @memberof Util
   */
  setCookie(name, value) {
    this.userModel = value;
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(JSON.stringify(value)) + ";expires=" + exp.toGMTString();
  }

  /**
   * 号码验证
   * @param {String} value 号码
   * @returns String
   * @memberof Certified
   */
  verification(value) {
    let info = '';
    if (value === '') {
      info = '号码不能为空';
    } else if (value.length < 11) {
      info = '号码少于11位';
    } else if (value.length > 11) {
      info = '号码大于11位';
    } else if (!(/^1[34578]\d{9}$/.test(value))) {
      info = '号码有误';
    }
    return info;
  }
  /**
   * http请求
   * @param {String} type 请求类型
   * @param {String} url 请求地址
   * @param {Object} obj 请求参数
   */
  getApiData(type = 'post', url, obj) {
    return new Promise((resolve) => {
      window.$http[type](`${window.$apiUrl}${url}`, obj).then((res) => {
        if (res.data.res !== 1) {
          window.$message.next({info: 'error', content: res.data.info.msg});
        }
        resolve(res);
      })
    })
  }

  /**
   * 读取cookie
   * @param {String} cname 名
   * @memberof Util
   */
  getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i].trim();
      if (c.indexOf(name) === 0) return JSON.parse(unescape(c.substring(name.length, c.length)));
    }
    return "";
  }

  /**
   * 修改浏览器title
   * @param {String} t 标题
   */
  setTitle(t) {
    document.title = t;
  }

  /**
   * 检测浏览器window.search是否有指定字段
   * @param {String} name 判断名字
   */
  getQueryStringByName(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return (r[2]);
    return null;
  };

  /**
   * 微信分享
   */
  wxShare() {
    const self = this;
    window.$http.post(`${window.$apiUrl}/svcBase/svcGetSignForUrl`, {
      url: window.location.href.split('#')[0]
      // url: encodeURIComponent(window.location.href.split('#')[0])
    }).then((data) => {
      const udata = data.data.info.uinfo;
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: udata.wx_appid,
        timestamp: udata.wx_utc,
        nonceStr: udata.wx_nonce,
        signature: udata.wx_sign,
        jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'] // 必填，需要使用的JS接口列表
      });
      wx.ready(() => {
        const obj = {
          title: '欢迎来到华亭哈密瓜农家果园',
          desc: '种植、生产、示范和旅游休闲于一体的哈密瓜产业基地！',
          link: `${window.$url}share`,
          imgUrl: 'http://botcdn.apiweixin.top/asserts/img/proj/qmshare.jpg',
          success: function (vs) {
            window.$http.post(`${window.$apiUrl}/svcBusiUser/svcShareResult`, {
              uid: self.userModel.uid,
              apptoken: self.userModel.apptoken,
              v_shtype: 'num_qq',
              v_shstatus: vs.errMsg
            })
          },
          fail: function (vs) {
            window.$http.post(`${window.$apiUrl}/svcBusiUser/svcShareResult`, {
              uid: self.userModel.uid,
              apptoken: self.userModel.apptoken,
              v_shtype: 'num_qq',
              v_shstatus: vs.errMsg
            })
          }
        };
        wx.onMenuShareAppMessage(obj);
        wx.onMenuShareQQ(obj);
        wx.onMenuShareWeibo(obj);
        wx.onMenuShareQZone(obj);
        wx.onMenuShareTimeline(obj);
      })
    })
  }
}

export default new Util();